import React, { useEffect, useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getList, setStatus, del, resetPwd } from '@/services/admin/auth/admin/api';
import { Switch, Space, message, Tag } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { exportExcel } from '@/utils/ExportExcel';
import { getSort, setLsetData } from '@/utils/utils';
import FormIndex from './components/FormIndex';
import CDel from '@/components/common/CDel';
import ResetPwd from './components/ResetPwd';
import { getGroupList, getProjectList } from '@/services/admin/common/api';
const Index: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [projectList, setProjectList] = useState<any>({});
  const [groupList, setGroupList] = useState<any>({});
  const fetchApi = async () => {
    const groupRes = await getGroupList();
    if (groupRes.status == 20000) {
      const groupData = [];
      for (let i = 0; i < groupRes.data.length; i++) {
        groupData[groupRes.data[i].id] = {
          text: groupRes.data[i].name,
          status: groupRes.data[i].id,
        };
      }
      if (groupData.length) await setGroupList({ ...groupData });
    }
    const projectRes = await getProjectList();
    if (projectRes.status == 20000) {
      const projectData = [];
      for (let i = 0; i < projectRes.data.length; i++) {
        projectData[projectRes.data[i].id] = {
          text: projectRes.data[i].name,
          status: projectRes.data[i].id,
        };
      }
      if (projectData.length) await setProjectList({ ...projectData });
    }
  };
  useEffect(() => {
    fetchApi();
  }, []);
  let maps = {};
  const columns: ProColumns<API.AdminAdminList>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      hideInSearch: true,
      align: 'center',
      width: 80,
      fixed: true,
    },
    {
      title: '账号',
      dataIndex: 'username',
      align: 'center',
      width: 100,
    },
    {
      title: '所属角色',
      dataIndex: 'admin_group',
      hideInSearch: true,
      width: 100,
      align: 'center',
      render: (text, record) => [<span key={record.id}>{record.admin_group?.name}</span>],
    },
    {
      title: '所属角色',
      dataIndex: 'group_id',
      valueType: 'select',
      valueEnum: groupList,
      hideInTable: true,
    },
    {
      title: '所属项目',
      dataIndex: 'project_value_arr',
      hideInSearch: true,
      width: 100,
      align: 'center',
      render: (text, record) => [
        record.project_value_arr.map((item: any) => {
          return <Tag color="volcano">{item.name}</Tag>;
        }),
      ],
    },
    {
      title: '所属项目',
      dataIndex: 'project_id',
      valueType: 'select',
      valueEnum: projectList,
      hideInTable: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      align: 'center',
      width: 100,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      align: 'center',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '禁用',
          status: '0',
        },
        1: {
          text: '启用',
          status: '1',
        },
      },
      hideInTable: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 100,
      align: 'center',
      render: (text, record) => [
        <Switch
          key={record.id + record.status}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.status === 1 ? true : false}
          disabled={record.id == 1 ? true : false}
          onChange={async (checked: boolean) => {
            const res = await setStatus(record.id, { status: checked ? 1 : 0 });
            if (res.status === 20000) {
              message.success(res.message);
            } else {
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      width: 180,
      align: 'center',
    },
    {
      title: '创建时间',
      key: 'created_at',
      dataIndex: 'created_at',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            'created_at[0]': value[0],
            'created_at[1]': value[1],
          };
        },
      },
    },
    {
      title: '更新时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      width: 180,
      align: 'center',
    },
    {
      title: '更新时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            updated_at: value,
          };
        },
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 280,
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      render: (_, row) => [
        <FormIndex
          id={row.id}
          key={row.id}
          disabled={row.id === 1}
          onConfirm={() => {
            return actionRef.current?.reload();
          }}
        />,
        <CDel
          disabled={row.id === 1}
          key={row.id}
          onCancel={async () => {
            const res = await del(row.id);
            if (res.status === 20000) {
              message.success(res.message);
              actionRef.current?.reload();
            }
          }}
        />,
        <ResetPwd
          disabled={row.id === 1}
          key={row.id}
          onCancel={async () => {
            const res = await resetPwd(row.id);
            if (res.status === 20000) {
              message.success(res.message);
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },
  ];
  return (
    <PageContainer fixedHeader={true} title={false}>
      <ProTable
        scroll={{ x: 1300 }}
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={async (params: API.ListQequest, sort) => {
          const data = await getSort(params, sort);
          const res = await getList(data);
          return setLsetData(res);
        }}
        options={{ fullScreen: true }}
        rowSelection={{ fixed: true }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        columnsState={{
          onChange: (map) => {
            maps = map;
          },
        }}
        tableAlertOptionRender={({ selectedRows }) => {
          return (
            <Space size={16}>
              <a
                onClick={() => {
                  const selectedRowsCope = JSON.parse(JSON.stringify(selectedRows));
                  selectedRowsCope.map((item: any) => {
                    item.admin_group = item.admin_group?.name || '';
                    const project_value_arr = [];
                    for (let i = 0; i < item.project_value_arr.length; i++) {
                      project_value_arr.push(item.project_value_arr[i].name);
                    }
                    item.project_value_arr = project_value_arr.join(',');
                    return item;
                  });
                  exportExcel({
                    fileName: '管理员',
                    columns,
                    maps,
                    selectedRows: selectedRowsCope,
                  });
                }}
              >
                导出数据
              </a>
            </Space>
          );
        }}
        headerTitle={
          <FormIndex
            onConfirm={() => {
              return actionRef.current?.reload();
            }}
          />
        }
      />
    </PageContainer>
  );
};
export default Index;
